<?php
/*
 * @Author: Wulala
 * @Date: 2025-04-08 11:46:09
 * @LastEditTime: 2025-04-11 16:15:06
 * @LastEditors: Wulala
 * @Description: 
 * @FilePath: \exchange\app\api\service\SignService.php
 * 可以输入预定的版权声明、个性签名、空行等
 */

namespace app\api\service\pay\lakala;


use think\facade\Cache;

class ApiService
{
    // 基础参数
    protected $config;//配置

    // 请求地址

    // token接口
    protected $getToken = 'auth/oauth/token';       //获取token
    protected $merchant = 'registration/merchant';       //商户进件

    protected $merchant_basic_update = 'merchants/channel/customer/update/basic'; //基础信息更新
    protected $merchant_settle_update = 'merchants/channel/customer/update/settle/$customerNo'; //结算信息更新
    protected $merchant_info = 'merchants/open/merchant/info'; //获取商户信息
    protected $addTerm = 'merchants/open/merchant/addTerm'; //增终进件
    protected $microTermList = 'merchants/open/merchant/microTermList'; //获取已绑定终端信息
    protected $subMerchantQuery = 'merchants/open/merchant/submer'; //新子商户查询

    protected $areaInfo = 'registration/organization/$parentCode';       //获取地区信息
    protected $bankAreaInfo  ='registration/organization/bank/$parentCode';       //获取银行地区信息
    protected $bankInfo  ='registration/bank';       //获取银行列表信息
    protected $shopType  ='registration/customer/category';       //商户类别查询
    protected $fileDo  ='registration/file/upload';       //文件上传下载
  

    // sdk接口
    protected $createPayOrder = '/api/v3/labs/trans/preorder';//1.支付预下单，获取订单号，支付结果回调通知
    protected $queryPayOrder = '/api/v3/labs/query/tradequery';//2.支付订单查询
    protected $cancelPayOrder = '/api/v3/labs/relation/refund';//3.取消订单,退单，可部分退款
    protected $cashierPayOrder = '/api/v3/ccss/counter/order/special_create';//4.收银台支付下单
    protected $cashierClosePayOrder = '/api/v3/ccss/counter/order/close';//5.收银台关单
    protected $cashierQueryPayOrder = '/api/v3/ccss/counter/order/query';//6.收银台支付查询
    protected $cashierCancelPayOrder = '/api/v3/lams/trade/trade_refund';//7.收银台支付取消
    protected $cashierCancelPayOrderQuery = '/api/v3/lams/trade/trade_refund_query';//8.收银台支付取消查询

    protected $applyLedgerMer = '/api/v2/mms/openApi/ledger/applyLedgerMer';//商户分账业务开通申请
    protected $applyLedgerReceiver = '/api/v2/mms/openApi/ledger/applyLedgerReceiver';//创建分账接收方
    protected $applyBind = '/api/v2/mms/openApi/ledger/applyBind';//分账关系绑定申请
    protected $balanceQuery = '/api/v2/laep/industry/ewalletBalanceQuery';//账户余额查询
    protected $balanceSeparate = '/api/v3/sacs/balanceSeparate';//分账
    protected $ewalletBalanceQuery = '/api/v2/laep/industry/ewalletBalanceQuery';//账管家余额查询
    protected $ewalletWithdrawD1 = '/api/v2/laep/industry/ewalletWithdrawD1';//账管家提现D1

    protected $uploadFile = '/api/v2/mms/openApi/uploadFile';//附件上传
    protected $cardBin = '/api/v2/mms/openApi/cardBin';//卡BIN查询

    protected $ecApply = '/api/v3/mms/open_api/ec/apply'; //入网协议申请
    protected $ecQuery = '/api/v3/mms/open_api/ec/q_status'; //入网协议查询


    /*
    * $config: 配置信息
    */
    public function __construct(array $config)
    {
        $this->config = $config;
    }

    // ---------------------------统一请求接口-------------------------

    //拉卡拉平台---统一请求接口---sdk---v3
    public function  sendV3Unite($urlApi,$data=[])
    {

        $config = new \Lakala\OpenAPISDK\V3\Configuration($this->config);

        $api = new \Lakala\OpenAPISDK\V3\Api\LakalaApi($config);

        $request = new \Lakala\OpenAPISDK\V3\Model\ModelRequest();
        // dump($data);exit;

        // 请求字段
        $request->setReqData($data);

        $response = $api->tradeApi($this->$urlApi, $request);

        return $response;
    }

    //拉卡拉平台---统一请求接口---sdk---v2
    public function  sendV2Unite($urlApi,$data=[])
    {

        $config = new \Lakala\OpenAPISDK\V2\V2Configuration($this->config);

        $api = new \Lakala\OpenAPISDK\V2\Api\V2LakalaApi($config);

        $request = new \Lakala\OpenAPISDK\V2\Model\V2ModelRequest();

        // 请求字段
        $request->setReqData($data);
// dump($this->$urlApi);
// dump($data);
        $response = $api->tradeApi($this->$urlApi, $request);
// dump($response);exit;

        return $response;
    }

    //拉卡拉平台---统一请求接口---token----新增
    public function  sendTokenUnite($urlApi='',$sendData=[],$postType='post',$contentType='json')
    {
        $url=$this->config['saas_url'].$this->$urlApi;

        $token=$this->getToken();

        $header='Authorization:bearer '.$token;

        preg_match_all('/\$(\w+)/', $url, $matches);
        if (!empty($matches[1])) {
            foreach ($matches[1] as $param) {
                if (isset($sendData[$param])) {
                    $url = str_replace('$' . $param, $sendData[$param], $url);
                }
            }
        }

        if($postType=='post'){
           $response=curl_post($url, $sendData, $header, $contentType);
        }else{
           $response=curl_get($url,$sendData,[$header]);
        }

        return json_decode($response,true);
    }

    //拉卡拉平台---统一请求接口---token-----编辑
    public function  sendUpdateTokenUnite($urlApi='',$sendData=[],$postType='post',$contentType='json')
    {
        $url=$this->config['saas_url'].$this->$urlApi;

        $token=$this->getUpdateToken();
        //dd('$token',$token);
        // $token = '624cd8f3-4f6d-4ec0-a70e-6c3292ea0d73';
        $header='Authorization:bearer '.$token;

        preg_match_all('/\$(\w+)/', $url, $matches);
        if (!empty($matches[1])) {
            foreach ($matches[1] as $param) {
                if (isset($sendData[$param])) {
                    $url = str_replace('$' . $param, $sendData[$param], $url);
                }
            }
        }

        if($postType=='post'){
            $response=curl_post($url, $sendData, $header, $contentType);
        }else{
            $response=curl_get($url,$sendData,[$header]);
        }

        return json_decode($response,true);
    }



    // -----------------------------------------统一返回接口--------------------------------

    // 拉卡拉平台---统一返回接口---sdk---v3
    public function  returnV3Unite($res=[])
    {
        if(isset($res['code'])&&$res['code']=='BBS00000'){
           return result_success('success',$res["resp_data"]);
        }else{
           return result_error($res["msg"]??'请求失败');
        } 

    }

    // 拉卡拉平台---统一返回接口---sdk---v2
    public function  returnV2Unite($res=[])
    {
        if(isset($res['retCode'])&&$res['retCode']=='000000'){
           return result_success('success',$res["respData"]);
        }else{
           return result_error($res["retMsg"]??'请求失败');
        } 

    }

    // 拉卡拉平台---统一返回接口--token
    public function  returnTokenUnite($res=[])
    {
        if(!isset($res['error'])){
           return result_success('success',$res);
        }else{
           return result_error($res["message"]??'请求失败');
        } 
    }



    // -----------------------------------------公共方法------------------------------------------


    //拉卡拉平台---获取Token
    public function getToken()
    {
        $key = 'lakala_create_token';
        if ( Cache::has($key) ) {
            $token = Cache::get($key);
        } else {
        $url=$this->config['saas_url'].$this->getToken;
        $dataToken['grant_type']='client_credentials';
        $dataToken['client_id']=$this->config['client_id'];
        $dataToken['client_secret']=$this->config['client_secret'];
        // var_dump($url);exit;

        $header='Authorization:Basic '.base64_encode($dataToken['client_id'].':'.$dataToken['client_secret']);
        $resData=curl_post($url, $dataToken, $header,'form-data');

        $res= json_decode($resData,true);

        if(isset($res["access_token"])){
            $token = $res['access_token'];
            Cache::set($key,$token, $res['expires_in']);
        } else {
            $token = '';
        }

        }
        return $token;
    }

    //拉卡拉平台---获取更改信息Token
    public function getUpdateToken()
    {
        $key = 'lakala_update_token';
        if ( Cache::has($key) ) {
            $token = Cache::get($key);
        } else {
            $url=$this->config['saas_url'].$this->getToken;
            $dataToken['grant_type']='password';
            $dataToken['client_id']=$this->config['client_id'];
            $dataToken['client_secret']=$this->config['client_secret'];
            $dataToken['username']=$this->config['username'];
            $dataToken['password']=$this->config['password'];
            $dataToken['scope']='all';

            $header='Authorization:Basic '.base64_encode($dataToken['client_id'].':'.$dataToken['client_secret']);
            $resData=curl_post($url, $dataToken, $header,'form-data');

            $res= json_decode($resData,true);

            if(isset($res["access_token"])){
                $token = $res['access_token'];
                Cache::set($key,$token, $res['expires_in']);
            } else {
                $token = '';
            }
        }
        return $token;
    }

    /**
     * 公钥解密
     * @param $data
     * @return string
     */
    public static function publicKeyDecrypt($data,$pubKey){

        $pubKey = "-----BEGIN PUBLIC KEY-----\n" .
            wordwrap($pubKey, 64, "\n", true)
            . "\n-----END PUBLIC KEY-----";

        $crypto = '';
        foreach (str_split(base64_decode($data), 128) as $chunk) {
            openssl_public_decrypt($chunk, $decryptData, $pubKey);
            $crypto .= $decryptData;
        }
        return $crypto;
    }

    /**
     * 私钥加密
     * @param $data
     * @return string
     */
    public static function privateKeyDecrypt($data,$privateKey){

        $privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($privateKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";
        $crypto = '';
        foreach (str_split($data, 117) as $chunk) {
            openssl_private_encrypt($chunk, $encryptData, $privateKey);
            $crypto .= $encryptData;
        }

        $encrypted = base64_encode($crypto);

        return $encrypted;
    }
}